import {Component, OnInit, ViewChild} from '@angular/core';
import {CamSearchTableComponent} from "../cam-search-table/cam-search-table.component";
import {FormBuilder, FormGroup} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {CamSearchService} from "../../shared/service/cam-search.service";
import {Vehicle} from "../../shared/model/vehicle";
import {Http} from "@angular/http";
import {Condition} from "../../shared/model/condition";
import {UserTableComponent} from "../../shared/component/user-table/user-table.component";
import {User} from "../../shared/model/user";
import {SingleOpenWinService} from "../../shared/service/single-open-win.service";
declare var $:any;

@Component({
  selector: 'app-cam-search-home',
  templateUrl: './cam-search-home.component.html',
  styleUrls: ['./cam-search-home.component.css']
})
export class CamSearchHomeComponent implements OnInit {

  vehicles:Vehicle[];
  selectedData = [];
  highForm:FormGroup;
  selectMeeting:Array<string> = [];
  allCheckbox:boolean = false;
  userId:string = this.routerInfo.snapshot.queryParams["userId"];     //当前登陆者ID

  @ViewChild(UserTableComponent) userTable :UserTableComponent;
  @ViewChild(CamSearchTableComponent) camSearchTable :CamSearchTableComponent;

  condition:Condition = new Condition();
  userSelected:User; //选择的申请人
  arr:string[]=["宝马","aa","aaa","b","bb","bbb","aab","aaaa","aaaaa","aaaaaa"];
  len:number=this.arr.length;


  //查询参数
  phase:string = "day";     //时间段  day(今天)， week(本周），month（本月），all（全部）
  vehicleName:string = "";       //车辆名称
  licenseNumber:string = "";   //车牌号
  status:number = -1;       //用车申请状态  0：审批中（流程进行中）；1：已审批（流程正常结案）；2：已撤销（申请人操作）；3：已终止（审批人操作） 4：取消（结案之后，派车之前，申请人可以取消出车申请）'
  applicant :string = ""; //申请人员（普通员工默认为登录者自己，车辆管理员可以选择）;
  statuses:any = [{
    "id":0,
    "name":"审批中"
  },{
    "id":1,
    "name":"已审批"
  },{
    "id":2,
    "name":"已撤销"
  },{
    "id":3,
    "name":"已终止"
  },{
    "id":4,
    "name":"已取消"
  }];
  startPick:any;
  endPick:any;
  disabled:boolean = true;
  display:string = "none";
  constructor(
    public fb:FormBuilder,
    private routerInfo:ActivatedRoute,
    private camSearchService:CamSearchService,
    private singleOpenWinService:SingleOpenWinService,
    private router:Router,
    private http:Http
  ) {


  }

  ngOnInit() {
    this.checkUser();//验证登录者

    this.createForm();

 //   this.onload();
    this.singleOpenWinService.valueChange.subscribe((info:string)=>{
      this.userSelected = this.userTable.selected;
      if(info == "applicant"){  //申请人开窗
        $("#applicantName").val(this.userSelected.name)
        $("#applicant").val(this.userSelected.id);
      }
      this.userIsVisible = false;
    });

  }

  //判断当前登录者是否是车辆管理员
  checkUser(){
    this.camSearchService.checkUser(this.userId).then(
      res =>{
        if(res.code === 1){
          this.disabled = false;//表示当前登录者是车辆管理员
        }else{
          this.disabled = true;
        }
        this.getCondition();
      }
    )
  }
  createForm(){
    this.highForm = this.fb.group({
      status:-1,
      applicantName:'',
      applicant:'',
      vehicleName:'',
      licenseNumber:''
    });
  }

  _current = 1;
  _pageSize = 10;
  _total = 1;
  _dataSet = [];
  _loading = true;



  //选择框
  _allChecked = false;
  // _indeterminate = false;
  _displayData: Array<any> = [];
  _checkedNumber = 0;
  _checkInfo= [];
  checkAllInfo = [];


  _checkAll(value) {
    if (value) {
      // this._displayData.forEach(data => data.checked = true);
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status!=0){
          this._displayData[i].checked = true;
        }
      }
    } else {
      this._displayData.forEach(data => data.checked = false);
      for(let i=0;i<this._displayData.length;i++){
        let numb = this.checkAllInfo.indexOf(this._displayData[i].oid);
        if(numb!=-1){
          this.checkAllInfo.splice(numb,1);
        }
      }
    }
    this._refreshStatus("","");
  };

  //当前页checkbox选中判断
  _refreshStatus(event,oid) {
    //全选判断
    if(this._displayData.length>0){
      let count:number = 0;
      let checkNumb:number = 0;
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status !=0){
          count++;
          if(this._displayData[i].checked == true){
            checkNumb++;
          }
        }
      }
      if(checkNumb!=0 && count==checkNumb){
        this._allChecked = true;
      }else{
        this._allChecked = false;
      }
    }
    this._checkedNumber = this._dataSet.filter(value => value.checked).length;
    this._checkInfo = this._dataSet.filter(value => value.checked);  //存放选中行的信息
    //判断是否有checkbox取消事件
    if(event==false){
      let numb = this.checkAllInfo.indexOf(oid);
      if(numb!=-1){
        this.checkAllInfo.splice(numb,1);
      }
    }
  };

  _displayDataChange($event) {
    this._displayData = $event;
  };

  //选择判断
  select(selectedData:any,currentData:any){
    let selectInfo = [];
    if(selectedData){
      for(var i=0;i<currentData.length;i++){
        for(var j=0;j<selectedData.length;j++){
          if(currentData[i].oid == selectedData[j]){
            selectInfo.push(currentData[i]);
          }
        }
      }
      selectInfo.forEach(data => data.checked = true);
    }
  }


  //将查询条件写入查询类
  getCondition(){
    this.condition.vehicelName = this.vehicleName;
    this.condition.userId = this.userId;
    this.condition.phase = this.phase;
    this.condition.licenseNumber = this.licenseNumber;
    if(this.disabled === true){
      this.condition.applicant = this.userId;
    }else {
      this.condition.applicant = this.applicant;
    }
    this.condition.status = this.status;
    this.camSearchService.change.emit(this.condition);
  }

  //简单查询清空
  btn_search_clear(){
    $('#name').val('');
  }
  //高级查询清空
  btn_detailedSearch_clear(){
    this.vehicleName= "";
    this.licenseNumber= "";
    this.status= -1;
    this.applicant= "";
    $('#applicantName').val('');
  }
  //简单查询
  btn_search(){
    this.btn_detailedSearch_clear();
    this.vehicleName = $('#name').val();
    this.camSearchTable._current = 1;
    this.camSearchTable.checkAllInfo = [];
    this.camSearchTable._checkInfo = [];
    this.getCondition();
  }
  //高级查询
  btn_detailedSearch(){
    this.btn_search_clear();
    this.showModal();
    if(this.disabled === true){
      $('#applicant').val(this.userId);
    }
    this.getVehicles();
  }

  //高级查询参数(modal)
  isVisible = false;

  showModal = () => {
    this.isVisible = true;
    $("#vehicleName").val(this.vehicleName);
    $("#licenseNumber").val(this.licenseNumber);
    $("#status").val(this.status);
  }

  //高级查询确定按钮
  detailedSearch(){
    this.status= $('#status').val();
    this.applicant= $('#applicant').val();
    this.licenseNumber = $("#licenseNumber").val();
    this.camSearchTable._current = 1;
    this.camSearchTable.checkAllInfo = [];
    this.camSearchTable._checkInfo = [];
    this.getCondition();
    this.isVisible = false;

    this.isVisible = false;
  }

  //页签切换
  pageChange(str:string){
    this.phase = str;
    this.camSearchTable._current = 1;
    this.getCondition();
  }

  //取消操作
  handleCancel = (e) => {
    this.isVisible = false;
  }


  //获取车辆信息
  getVehicles(){
    this.camSearchService.getVehicles().then(res => {
      this.vehicles = res;
    });
  }

  //用车申请
  btn_apply(){
    this.router.navigate(["camApplyByUser"],{queryParams:{userId:this.userId,flag:"search"}});
  }

  //车辆名称预加载
  onload(){
    let input=document.getElementById("name");
    let ul=document.getElementById("strul");
    ul.style.position="absolute";
    ul.style.top=(input.offsetTop+input.offsetHeight)+"px";
    ul.style.left=input.offsetLeft+"px";


    //根据输入匹配，显示下拉框
    $("#name").selectedIndex=-1;
      input.focus();
    }

  onkeyup(event:any){
    let ul=document.getElementById("strul");
    ul.innerHTML="";
    ul.style.borderWidth="1px";
    ul.style.borderStyle="none   ";
    ul.style.borderColor="#999";
    ul.style.fontFamily="Arial,Microsoft JhengHei,sans-serif,微軟正黑體";
    ul.style.fontSize="12px";
    var value= $("#name").val();
    if(value){
      var reg=new RegExp("^"+value+"+");//当输入框为空的时候会报错
      for(var i=0;i<this.len;i++){
        if(reg.test(this.arr[i])){
          var li=document.createElement("li");
          //匹配部分变粗
          var matchlen=value.length;
          var string=this.arr[i].substr(matchlen);
          li.innerHTML="<strong>"+value+"</strong>"+string;
          //li.style.listStyle="none";
          li.style.fontFamily="Arial,Microsoft JhengHei,sans-serif,微軟正黑體";
          li.style.fontSize="12px";
          li.onmouseover =function () {
            this.style.backgroundColor="#ececec";
          }
          li.onmouseout =function () {
            this.style.backgroundColor="#fff";
          }
          li.onclick =function(){
            $("#name").val(this.innerText||this.textContent);
            ul.innerHTML="";
            ul.style.border="none";
          }
          ul.appendChild(li);
        }
      }

    }
    if(ul.innerHTML){
      ul.style.display = "block";
    }else{
      ul.style.display = "none";
    }
    $("#name").options=li;

  }
  /**
   *  单选人员开窗
   */
  userIsVisible = false;

  userShowModal = () => {
    this.userIsVisible = true;
  }

  userHandleCancel = (e) => {
    this.userIsVisible = false;
  }

  //人员查询
  openwin(){
    this.userTable.source = "applicant";
    this.userShowModal();
  }

  //车辆名称选中
  onselected(){
    if(this.vehicleName !==""){
      let cam:Vehicle = this.vehicles.find((r) => (r.oid === this.vehicleName) );
      this.licenseNumber = cam.oid;
      this.vehicleName = cam.oid;
    }else{
      this.licenseNumber = "";
    }
  }


  //车牌号选中
  onselected1(){
    if(this.licenseNumber !== ""){
      let cam:Vehicle = this.vehicles.find((r) => (r.oid === this.licenseNumber) );
      this.vehicleName = cam.oid;
      this.licenseNumber = cam.oid;
    }else {
      this.vehicleName = "";
    }

  }

  //清空申请人栏位
  clear(){
    $("#applicantName").val('');
    $("#applicant").val('');
  }

  //删除
  delData() {
    this.camSearchTable.delInfo();
  }
}
